package cn.supermarket.controller.common;

import cn.supermarket.common.config.ProjectConfig;
import cn.supermarket.common.contant.CacheConstants;
import cn.supermarket.common.contant.Constants;
import cn.supermarket.common.core.entity.Result;
import cn.supermarket.common.utils.CaffeineUtils;
import cn.supermarket.common.utils.sign.Base64;
import cn.supermarket.common.utils.uuid.IdUtils;
import cn.supermarket.system.service.SysConfigService;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码操作处理
 * @Author yp
 * @Date 2024/2/9:12:47
 */
@RestController
@Api(value = "验证码操作处理", tags = "验证码操作处理")
public class CaptchaController
{
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private SysConfigService sysConfigService;


    @Autowired
    private LoadingCache captchaCache;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    @ApiOperation("生成验证码")
    public Result getCode(HttpServletResponse response) throws IOException
    {
        Result result = Result.success();
        boolean captchaEnabled = sysConfigService.selectCaptchaEnabled();
        result.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled)
        {
            return result;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = ProjectConfig.getCaptchaType();
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        CaffeineUtils.put(captchaCache,getCacheKey(uuid),code);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return Result.error(e.getMessage());
        }

        result.put("uuid", uuid);
        result.put("img", Base64.encode(os.toByteArray()));
        return result;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey)
    {
        return CacheConstants.CAPTCHA_CODE_KEY + configKey;
    }
}
